<?php

namespace App\Http\Controllers\Admin;

use App\Services\WxMassService;
use App\Services\WxUserTagService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * 微信群发管理
 * @package App\Http\Controllers\Admin
 */
class WxMassController extends BaseController
{
    private $wxMassSer;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->wxMassSer = new WxMassService();
    }

    /**
     * 群发列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $pageSize = $request->get('pageSize', 10);
            $query = \App\Models\WxMass::select('*');
            $keyword = $request->get('keyword', '');
            if ($keyword) {
                $query->where('title', 'like', '%' . $keyword . '%');
            }
            $data = $query->orderBy('mass_id', 'DESC')->paginate($pageSize)->toArray();
            if ($data['data']){
                $replyList = $data['data'];
                foreach ($replyList as $k => $v){
                    $v['msg_type_str'] = $this->wxMassSer->getMsgTypeStr($v['msg_type']);
                    $replyList[$k] = $v;
                }
                $data['data'] = $replyList;
            }

            return $data;
        }
        //群发速度配置
        $speedType = $this->wxMassSer->getSpeedTypeList();
        $this->viewData['speedType'] = $speedType;
        return view('admin.wxmass.index', $this->viewData);
    }

    /**
     * 添加或编辑页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function form(Request $request)
    {
        $id = $request->get('id', 0);
        $autoreplyData = [
            'name' => '', 'keywords' => [], 'is_open' => 0,
            'start_time' => '', 'end_time' => '',
            'msg_type' => 'text', 'order_num' => 0, 'content' => '',
            'filter_rule' => [
                'type' => 'all',
            ],
        ];
        if ($id) {
            $autoreply = \App\Models\WxMass::with('material')->findOrFail($id);
            $autoreplyData = $autoreply->toArray();
        }
        //空素材数据
        if (empty($autoreplyData['material'])){
            $autoreplyData['material'] = [
                'title' => '',
            ];
        }
        $this->viewData['massData'] = $autoreplyData;
        //用户筛选类别
        $this->viewData['filterTypeList'] = (new \App\Services\WxMass\FilterFactory())->getFilterTypeList();
        //回复类型列表
        $msgTypeList = $this->wxMassSer->getMsgTypeList();
        $this->viewData['msgTypeList'] = $msgTypeList;
        //用户标签列表
        $tagList = (new WxUserTagService())->getTagList();
        $tagList && $tagList = $tagList->toArray();
        //树结构菜单列表
        $tree = new \App\Services\TreeService('tag_id', 'parent_id', 'children');
        $tree->load($tagList);
        $treeTagList = $tree->deepTree();
        $this->viewData['tagList'] = $treeTagList ? $treeTagList : [];

        return view('admin.wxmass.form', $this->viewData);
    }

    /**
     * 群发保存
     * @param \App\Http\Requests\AdminWxMassPost $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminWxMassPost $request)
    {
        try {
            $rs = $this->wxMassSer->save($request);
            if ($rs) {
                return $this->showMsg('success', ($request->input('id') ? '编辑' : '添加') . '群发成功', [], 'admin.wxmass.index');
            }
            throw new \Exception(($request->input('id') ? '编辑' : '添加') . '群发失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 删除群发
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        try {
            $massId = $request->input('mass_id', 0);
            if (empty($massId)) {
                throw new \Exception('请指定要删除的群发');
            }
            $rs = $this->wxMassSer->del($massId);
            if (!$rs) {
                throw new \Exception('删除失败');
            }
            return $this->showMsg('success', '删除成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 发送群发预览
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function preview(Request $request)
    {
        try {
            $massId = $request->input('mass_id', 0);
            if (empty($massId)) {
                throw new \Exception('请指定要预览的群发');
            }
            $to = $request->input('to', '');
            if (empty($to)){
                throw new \Exception('请输入用户标识');
            }
            $msgType = $request->input('msg_type', '');
            $rs = $this->wxMassSer->createMassObject($msgType)->handleSend($massId);
            //$rs = $this->wxMassSer->createMassObject($msgType)->preview($massId, $to);
            if (!$rs) {
                throw new \Exception('预览发送失败');
            }
            return $this->showMsg('success', '发送预览成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 同步群发消息发送状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function syncStatus(Request $request)
    {
        try {
            $massId = $request->input('mass_id', 0);
            if (!$massId) {
                throw new \Exception('请指定要刷新状态的群发');
            }
            $rs = $this->wxMassSer->status($massId);
            if (!$rs) {
                throw new \Exception('预刷新失败失败');
            }
            return $this->showMsg('success', '刷新成功成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 设置群发速度
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function upSetSpeed(Request $request)
    {
        if ($request->ajax()) {
            if ($request->isMethod('GET')){//获取群发速度
                try {
                    $speedData = $this->wxMassSer->getSpeed();
                    if (!$speedData) {
                        throw new \Exception('获取群发速度失败');
                    }
                    return $this->showMsg('success', '获取群发速度成功', $speedData);
                } catch (\Exception $e) {
                    return $this->showMsg('error', $e->getMessage());
                }
            }
            if ($request->isMethod('POST')){//保存群发速度
                try {
                    $speed = $request->input('speed', 0);
                    $rs = $this->wxMassSer->saveSpeed($speed);
                    if (!$rs) {
                        throw new \Exception('设置群发失败');
                    }
                    return $this->showMsg('success', '设置群发成功');
                } catch (\Exception $e) {
                    return $this->showMsg('error', $e->getMessage());
                }
            }
        }
    }
}
